<?php

namespace App\Store\Models\Message;

use App\Common\Services\Common;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Score extends Model
{
    protected $table = 'site_message_score';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     * 获取列表
     */
    public static function getList(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['storeinfo'])->where(['cp_id' => $cp_id, 'is_del' => 1]);

        // 标题
        $title = $request['title'] ?? '';
        if ($title !== '') {
            $query->where('title', 'like', '%' . $title . '%');
        }

        // 时间筛选
        $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : (int)$request->start_time;
        $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : (int)$request->end_time;
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        }

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if ($store_ids) { //权限控制
            if (is_array($store_ids)) { //获取当前权限下的门店
                $query->whereIn('store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }

        $query->orderBy('create_at', 'desc');

        $isgetall = $request['isgetall'] ?? 0;
        if ($isgetall === 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        }

        $list = $query->get()->toArray();
        return ['list' => $list];
    }

    /**
     * 店铺
     */
    public function storeinfo()
    {
        return $this->hasOne(SiteStore::class, 'id', 'store_id')->select('id', 'store_name');
    }
}
